package com.agger.harmonyosthemeseditor.abilities.slices;

import com.agger.harmonyosthemeseditor.ResourceTable;
import com.agger.harmonyosthemeseditor.ThemesEditorAbility;
import com.agger.harmonyosthemeseditor.abilities.PreloadServiceAbility;
import com.agger.harmonyosthemeseditor.intelligent.*;
import com.agger.harmonyosthemeseditor.userinterface.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.bundle.IBundleManager;
import ohos.data.rdb.ValuesBucket;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.ResourceManager;
import ohos.media.image.PixelMap;
import ohos.media.image.common.ImageInfo;
import ohos.media.photokit.metadata.AVStorage;
import ohos.os.ProcessManager;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class SmartIconSlice extends AbilitySlice
{
    private final int ChooseImage_Mask = 1003;
    private final int ChooseImage_Foreground = 1004;
    private final int ChooseImage_Background = 1005;
    PixelMap pxm = null;
    TextField textBox_ChineseName = null;
    TextField textBox_InternationalName = null;
    TextField textBox_DesignerName = null;
    TextField textBox_VersionCode = null;
    TextField textBox_BriefInfo = null;
    Component text_ChineseName = null;
    Component text_InternationalName = null;
    Component text_DesignerName = null;
    Component text_VersionCode = null;
    Component mask_border01 = null;
    Component mask_method01 = null;
    Component mask_border02 = null;
    Component mask_method02 = null;
    Component mask_border03 = null;
    Component mask_method03 = null;
    Component mask_border04 = null;
    Component mask_method04 = null;
    Component mask_border05 = null;
    Image mask_method05 = null;
    String Dialog_Title = "爱洁羊智慧能力";
    String Dialog_Content_StoragePermissionFailed = "存储功能被禁用，请前往应用管理页，开启主题协作器的存储权限！";
    String Dialog_Button_Cancel = "取消";
    String Dialog_Button_Confirm = "好的";
    String Toast_NoneName = "请录入主题包名称！汉语名称、国际名称，至少填写一项！";
    String Toast_NoneDesigner = "请录入主题包的设计师名称！";
    String Toast_NoneVersion = "请录入主题包的版本号码！";
    String Toast_NoneBriefInfo = "请录入主题包的简单介绍信息！";
    String Toast_IsProcessing = "主题生成中，请勿进行其它操作！";
    String Toast_Theme_SaveFinish = "主题包已存储至";
    String Toast_Theme_SaveFailed = "存储主题包时出现错误，请确保设备容量充足！";
    MainThreadEventHandler mainThreadEventHandler;
    PacThemeEventHandler PacThemeEventHandler;
    ScreenEventHandler screenEventHandler;
    Text text_ColorSelector = null;
    Text text_ForegroundSelector = null;
    Text text_BackgroundSelector = null;
    Text text_IconSize = null;
    Slider SizeSlider = null;
    String ElementColor = "FF8362";
    boolean isProcessing = false;
    boolean isSuccess = false;
    boolean BigSuccess = false;
    ColorDialog colorDialog = null;
    String ThemesDate = "20220222022022";
    int MaskMode = 0;

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation)
    {
        super.onOrientationChanged(displayOrientation);
        try
        {
            if(!colorDialog.isDestroyed)
            {
                if(!colorDialog.isShowing())
                {
                    colorDialog.setDestroyedListener(null);
                    colorDialog.destory();
                    colorDialog = null;
                    System.gc();
                }
                else
                {
                    colorDialog.setDestroyedListener(null);
                    colorDialog.saveTempColorValue();
                    colorDialog.destory();
                    colorDialog = null;
                    System.gc();
                    recoverDialog_ColorSelector();
                }
            }
        }catch (Exception ex){}
        try
        {
            DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
            int maxTextWidth = displayAttributes.width-(int)(216f*displayAttributes.scalDensity+0.5f);
            text_ChineseName.setLayoutRefreshedListener(null);
            text_InternationalName.setLayoutRefreshedListener(null);
            text_DesignerName.setLayoutRefreshedListener(null);
            text_VersionCode.setLayoutRefreshedListener(null);
            text_ChineseName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_InternationalName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_DesignerName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_VersionCode.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_ChineseName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_InternationalName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_DesignerName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_VersionCode.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        }catch (Exception e){}
    }

    private class PacThemeEventHandler extends EventHandler
    {
        private PacThemeEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if (event == null)
            {
                return;
            }
            isSuccess = false;
            BigSuccess = false;
            ProcessManager.setThreadPriority(-20);
            String workPath = getCacheDir() + "/SmartIconArea";
            File WorkStorage = new File(workPath);
            if(WorkStorage.exists())FileManager.deleteDirectory(workPath,true,false);
            new File(workPath+"/preview").mkdirs();
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/unlock_slide",workPath+"/unlock");
            FileManager.copyFile(getFilesDir()+"/ThemesTemplate/preview/preview_unlock_0.jpg",workPath+"/preview/cover.jpg");
            FileManager.copyFile(getFilesDir()+"/ThemesTemplate/preview/preview_unlock_0.jpg",workPath+"/preview/preview_unlock_0.jpg");
            FileManager.copyFile(getFilesDir()+"/ThemesTemplate/preview/preview_icons_0.jpg",workPath+"/preview/preview_icons_0.jpg");
            FileManager.copyFile(getFilesDir()+"/ThemesTemplate/description.xml",workPath+"/description.xml");
            File xmlFile = new File(workPath+"/description.xml");
            try
            {
                FileInputStream in = new FileInputStream(xmlFile);
                byte[] b = new byte[(int) xmlFile.length()];
                in.read(b);
                String xmlText = new String(b);
                in.close();
                xmlText = xmlText.replaceAll("汉语名称",textBox_ChineseName.getText());
                xmlText = xmlText.replaceAll("国际名称",textBox_InternationalName.getText());
                xmlText = xmlText.replaceAll("设计师名",textBox_DesignerName.getText());
                xmlText = xmlText.replaceAll("版本号码",textBox_VersionCode.getText());
                xmlText = xmlText.replaceAll("简介信息",textBox_BriefInfo.getText());
                FileOutputStream out = null;
                try
                {
                    out = new FileOutputStream(xmlFile);
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
                    writer.write(xmlText);
                    writer.close();
                    out.flush();
                    out.close();
                }catch(IOException ex){ex.printStackTrace();}
                finally
                {
                    try
                    {
                        if (out != null)
                        {
                            out.close();
                        }
                    } catch(IOException e){}
                }
            }catch(IOException ex) {}
            String iconPath = getCacheDir() + "/SmartIconArea_Temp";
            File IconStorage = new File(iconPath);
            if(IconStorage.exists())FileManager.deleteDirectory(iconPath,true,false);
            IconStorage.mkdirs();

            PixelMap mask = null;
            if(MaskMode==0)
            {
                mask = GeneralUtil.getPixelMapFromRawFile(getContext(),"mask_rectangle");
                GeneralUtil.writeRawFileToFile(getContext(),"mask_rectangle",iconPath+"/icon_mask.png");
            }
            else if(MaskMode==1)
            {
                mask = GeneralUtil.getPixelMapFromRawFile(getContext(),"mask_oval");
                GeneralUtil.writeRawFileToFile(getContext(),"mask_oval",iconPath+"/icon_mask.png");
            }
            else if(MaskMode==2)
            {
                mask = GeneralUtil.getPixelMapFromRawFile(getContext(),"mask_butterfly");
                GeneralUtil.writeRawFileToFile(getContext(),"mask_butterfly",iconPath+"/icon_mask.png");
            }
            else if(MaskMode==3)
            {
                mask = GeneralUtil.getPixelMapFromRawFile(getContext(),"mask_diamond");
                GeneralUtil.writeRawFileToFile(getContext(),"mask_diamond",iconPath+"/icon_mask.png");
            }
            else if(MaskMode==4)
            {
                if(new File(getCacheDir() + "/SmartIcon/Mask.png").exists())
                {
                    mask = IconManager.ResizeImage(GeneralUtil.getPixelMapFromFile(new File(getCacheDir() + "/SmartIcon/Mask.png")),192,192);
                    FileManager.copyFile(getCacheDir() + "/SmartIcon/Mask.png",iconPath+"/icon_mask.png");
                }
                else
                {
                    mask = GeneralUtil.getPixelMapFromRawFile(getContext(),"mask_rectangle");
                    GeneralUtil.writeRawFileToFile(getContext(),"mask_rectangle",iconPath+"/icon_mask.png");
                }
            }else
            {
                mask = GeneralUtil.getPixelMapFromRawFile(getContext(),"mask_rectangle");
                GeneralUtil.writeRawFileToFile(getContext(),"mask_rectangle",iconPath+"/icon_mask.png");
            }
            if(mask==null) mask = GeneralUtil.getPixelMapFromRawFile(getContext(),"mask_rectangle");
            FileManager.copyFile(iconPath+"/icon_mask.png",iconPath+"/icon_shortcut_mask.png");

            PixelMap foreground = null;
            boolean fastMode = false;
            if(new File(getCacheDir() + "/SmartIcon/Foreground.png").exists())
            {
                PixelMap m = GeneralUtil.getPixelMapFromFile(new File(getCacheDir() + "/SmartIcon/Foreground.png"));
                try
                {
                    ImageInfo imageInfo = m.getImageInfo();
                    if(imageInfo.size.width==192&&imageInfo.size.height==192)
                    {
                        foreground = m;
                        if(!IconManager.isAlphaImage(foreground))fastMode = true;
                    }else
                    {
                        foreground = ImageIntelligent.ResizeImage(m,192,192);
                        if(!IconManager.isAlphaImage(foreground))
                        {
                            fastMode = true;
                        }
                    }
                }catch (Exception ex){}
            }
            PixelMap background = null;
            if(new File(getCacheDir() + "/SmartIcon/Background.png").exists())
            {
                PixelMap m = GeneralUtil.getPixelMapFromFile(new File(getCacheDir() + "/SmartIcon/Background.png"));
                try
                {
                    ImageInfo imageInfo = m.getImageInfo();
                    if(imageInfo.size.width==192&&imageInfo.size.height==192)
                    {
                        background = IconManager.isAlphaImage(m)?IconManager.coverIcon(m,IconManager.getVirtualBackground(Color.getIntColor(text_ColorSelector.getText()))):m;
                    }else
                    {
                        if(!IconManager.isAlphaImage(m))
                            background = ImageIntelligent.ResizeImage(m,192,192);
                        else
                            background = IconManager.coverIcon(ImageIntelligent.ResizeImage(m,192,192),IconManager.getVirtualBackground(Color.getIntColor(text_ColorSelector.getText())));
                    }
                }catch (Exception ex){}
            }
            if(background==null) background=IconManager.getVirtualBackground(Color.getIntColor(text_ColorSelector.getText()));

            int size = DatabaseManager.getInt("IconElementRealSize",192);

            //boolean result = true;
            boolean result = IconManager.ProcessAllAppIcons(getAbility(),Color.getIntColor(text_ColorSelector.getText()),foreground,background,size,mask,iconPath,fastMode);
            if(result)
            {
                try{ZipFileManager.zip(iconPath,workPath+"/icons");}catch(Exception e){}

                try
                {
                    if(!new File(getCacheDir()+"/Project_Themes").exists()) new File(getCacheDir()+"/Project_Themes").mkdirs();
                    ZipFileManager.zip(workPath,getCacheDir()+"/Project_Themes/"+textBox_InternationalName.getText()+".hwt");
                    InputStream input = null;
                    try
                    {
                        input = new FileInputStream(getCacheDir()+"/Project_Themes/"+textBox_InternationalName.getText()+".hwt");
                        ValuesBucket valuesBucket = new ValuesBucket();
                        valuesBucket.putString(AVStorage.Downloads.DISPLAY_NAME, textBox_InternationalName.getText()+".hwt");
                        valuesBucket.putString("relative_path", "Download/ThemesEditor/");
                        valuesBucket.putInteger("is_pending", 1);
                        DataAbilityHelper helper = GeneralUtil.createDataAbilityHelper(getContext());
                        int id = helper.insert(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
                        Uri uri = Uri.appendEncodedPathToUri(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
                        FileDescriptor fd = helper.openFile(uri, "w");
                        OutputStream output= new FileOutputStream(fd);
                        byte[] buf = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = input.read(buf)) > 0)
                        {
                            output.write(buf, 0, bytesRead);
                        }
                        output.flush();
                        output.close();
                        valuesBucket.clear();
                        valuesBucket.putInteger("is_pending", 0);
                        helper.update(uri, valuesBucket, null);
                        isSuccess = true;
                        ThemesDate = GeneralUtil.getTimeStr();
                        //部分机型未限制存储分区，可直接将主题包复制到/Huawei/Themes目录
                        Files.copy(new File(getCacheDir()+"/Project_Themes/"+textBox_InternationalName.getText()+".hwt").toPath(),new File("/storage/emulated/0/Huawei/Themes/"+ThemesDate+".hwt").toPath(), StandardCopyOption.REPLACE_EXISTING);
                        BigSuccess = true;
                    }catch (Exception ex) {}
                    finally {input.close();}
                }catch (Exception e){e.printStackTrace();}
            }
            mainThreadEventHandler.sendEvent(0,0,EventHandler.Priority.IMMEDIATE);
        }
    }

    private class MainThreadEventHandler extends EventHandler
    {
        private MainThreadEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if (event == null)
            {
                return;
            }
            if(BigSuccess)
            {
                new GeneralToast(getContext())
                        .setText(Toast_Theme_SaveFinish+"Huawei/Themes/"+ThemesDate+".hwt")
                        .show();
            }else
            {
                new GeneralToast(getContext())
                        .setText(isSuccess?(Toast_Theme_SaveFinish+"Download/ThemesEditor/"+textBox_InternationalName.getText()+".hwt"):Toast_Theme_SaveFailed)
                        .show();
            }

            isProcessing = false;
            textBox_ChineseName.setEnabled(true);
            textBox_InternationalName.setEnabled(true);
            textBox_DesignerName.setEnabled(true);
            textBox_VersionCode.setEnabled(true);
            textBox_BriefInfo.setEnabled(true);
            SizeSlider.setEnabled(true);
            textBox_ChineseName.setClickedListener(null);
            textBox_InternationalName.setClickedListener(null);
            textBox_DesignerName.setClickedListener(null);
            textBox_VersionCode.setClickedListener(null);
            textBox_BriefInfo.setClickedListener(null);
            screenEventHandler.sendSyncEvent(0,EventHandler.Priority.IMMEDIATE);
        }
    }

    private class ScreenEventHandler extends EventHandler
    {
        private ScreenEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if(event == null) return;
            if(event.eventId == 0) {try{getWindow().clearFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS);}catch (Exception e){}}
            else {try{getWindow().addFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS);}catch (Exception e){}}
        }
    }

    @Override
    public void onStart(Intent intent)
    {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_smart_icon);
        this.getWindow().setStatusBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xF7EDD8));
        this.getWindow().setNavigationBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_navigationbar_normal,0xF7EDD8));
        int CurrentColorMode = getColorMode();
        if(CurrentColorMode == 0) this.getWindow().setStatusBarVisibility(0);
        else if(CurrentColorMode == 1) this.getWindow().setStatusBarVisibility(2052);
        this.getWindow().setBackgroundColor(RgbColor.fromArgbInt(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xFEEFF4)));
        ThemesEditorAbility.Instance.eventRunner = EventRunner.current();
        mainThreadEventHandler = new MainThreadEventHandler(EventRunner.current());
        screenEventHandler = new ScreenEventHandler(EventRunner.current());
        GeneralUtil.setWindowToMaxRefreshRate(getWindow());
        GeneralUtil.setWindowSoftInputMode(getWindow(),GeneralUtil.SOFT_INPUT_ADJUST_PAN);
        try
        {
            if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
            {
                if (canRequestPermission("ohos.permission.READ_USER_STORAGE")&&canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
                    requestPermissionsFromUser(new String[] { "ohos.permission.READ_USER_STORAGE","ohos.permission.WRITE_USER_STORAGE"} ,2);
            }
        }catch(Exception ex){}
        ResourceManager resManager = getResourceManager();
        try
        {
            Dialog_Title = resManager.getElement(ResourceTable.String_Dialog_Title).getString();
            Dialog_Content_StoragePermissionFailed = resManager.getElement(ResourceTable.String_Dialog_Content_StoragePermissionFailed).getString();
            Dialog_Button_Cancel = resManager.getElement(ResourceTable.String_Dialog_Button_Cancel).getString();
            Dialog_Button_Confirm = resManager.getElement(ResourceTable.String_Dialog_Button_Confirm).getString();
            Toast_NoneName = resManager.getElement(ResourceTable.String_ThemeToast_NoneName).getString();
            Toast_NoneDesigner = resManager.getElement(ResourceTable.String_ThemeToast_NoneDesigner).getString();
            Toast_NoneVersion = resManager.getElement(ResourceTable.String_ThemeToast_NoneVersion).getString();
            Toast_NoneBriefInfo = resManager.getElement(ResourceTable.String_ThemeToast_NoneBriefInfo).getString();
            Toast_IsProcessing = resManager.getElement(ResourceTable.String_ThemeToast_IsProcessing).getString();
            Toast_Theme_SaveFinish = resManager.getElement(ResourceTable.String_ThemeToast_SaveFinish).getString();
            Toast_Theme_SaveFailed = resManager.getElement(ResourceTable.String_ThemeToast_SaveFailed).getString();
        }catch (Exception e){}
        isProcessing = false;
        textBox_ChineseName = (TextField) findComponentById(ResourceTable.Id_textBox_chineseName);
        textBox_InternationalName = (TextField) findComponentById(ResourceTable.Id_textBox_internationalName);
        textBox_DesignerName = (TextField) findComponentById(ResourceTable.Id_textBox_designerName);
        textBox_VersionCode = (TextField) findComponentById(ResourceTable.Id_textBox_versionCode);
        textBox_BriefInfo = (TextField) findComponentById(ResourceTable.Id_textBox_briefInfo);
        TextBoxManager.TextBoxForStyle(this,textBox_ChineseName);
        TextBoxManager.TextBoxForStyle(this,textBox_InternationalName);
        TextBoxManager.TextBoxForStyle(this,textBox_DesignerName);
        TextBoxManager.TextBoxForStyle(this,textBox_VersionCode);
        TextBoxManager.TextBoxForStyle(this,textBox_BriefInfo);
        DatabaseManager.Init(this);
        textBox_ChineseName.setText(DatabaseManager.getString("SmartIcon_ChineseName"));
        textBox_InternationalName.setText(DatabaseManager.getString("SmartIcon_InternationalName"));
        textBox_DesignerName.setText(DatabaseManager.getString("SmartIcon_DesignerName"));
        textBox_VersionCode.setText(DatabaseManager.getString("SmartIcon_VersionCode"));
        textBox_BriefInfo.setText(DatabaseManager.getString("SmartIcon_BriefInfo"));
        textBox_ChineseName.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_ChineseName.setText(TextManager.removeSpecificCharArray(textBox_ChineseName.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("SmartIcon_ChineseName",textBox_ChineseName.getText());
            }
            catch (Exception e){}
        });
        textBox_InternationalName.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_InternationalName.setText(TextManager.removeSpecificCharArray(textBox_InternationalName.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("SmartIcon_InternationalName",textBox_InternationalName.getText());
            }
            catch (Exception e){}
        });
        textBox_DesignerName.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_DesignerName.setText(TextManager.removeSpecificCharArray(textBox_DesignerName.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("SmartIcon_DesignerName",textBox_DesignerName.getText());
            }
            catch (Exception e){}
        });
        textBox_VersionCode.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                String VersionCodeText = "";
                char[] texts = textBox_VersionCode.getText().toCharArray();
                char last = '?';
                for(int o=0;o<texts.length;o++)
                {
                    if(TextManager.isNumChar(texts[o]))
                    {
                        if(texts[o]!=last||texts[o]!='.')
                        {
                            VersionCodeText += texts[o];
                            last = texts[o];
                        }
                    }
                }
                if(VersionCodeText.startsWith("."))
                {
                    VersionCodeText = "12"+VersionCodeText;
                }else if(VersionCodeText.startsWith("0"))
                {
                    VersionCodeText = "12";
                }else if(VersionCodeText.startsWith("0.")||VersionCodeText.startsWith("1.")||VersionCodeText.startsWith("2.")||VersionCodeText.startsWith("3.")||VersionCodeText.startsWith("4.")||VersionCodeText.startsWith("5.")||VersionCodeText.startsWith("6.")||VersionCodeText.startsWith("7.")||VersionCodeText.startsWith("8.")||VersionCodeText.startsWith("9.")||VersionCodeText.startsWith("10.")||VersionCodeText.startsWith("11."))
                {
                    VersionCodeText = "12"+VersionCodeText.substring(VersionCodeText.indexOf('.'));
                }
                textBox_VersionCode.setText(VersionCodeText);
                DatabaseManager.Init(this);
                DatabaseManager.setString("SmartIcon_VersionCode",VersionCodeText);
            }
            catch (Exception e){}
        });
        textBox_BriefInfo.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_BriefInfo.setText(TextManager.removeSpecificCharArray(textBox_BriefInfo.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("SmartIcon_BriefInfo",textBox_BriefInfo.getText());
            }
            catch (Exception e){}
        });
        text_ChineseName = findComponentById(ResourceTable.Id_text_chineseName);
        text_InternationalName = findComponentById(ResourceTable.Id_text_internationalName);
        text_DesignerName = findComponentById(ResourceTable.Id_text_designerName);
        text_VersionCode = findComponentById(ResourceTable.Id_text_versionCode);
        DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
        int maxTextWidth = displayAttributes.width-(int)(216f*displayAttributes.scalDensity+0.5f);
        text_ChineseName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        text_InternationalName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        text_DesignerName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        text_VersionCode.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        DatabaseManager.Init(this);
        ElementColor = DatabaseManager.getString("SmartIcon_ElementColor","FF8362");
        text_ColorSelector = (Text) findComponentById(ResourceTable.Id_colorBox_mainColor);
        text_ColorSelector.setText("#"+ElementColor);
        text_ColorSelector.setClickedListener(c ->
        {
            if(!isProcessing)
            {
                if(colorDialog==null)
                    showDialog_ColorSelector();
                else
                {
                    if(!colorDialog.isDestroyed)
                    {
                        colorDialog.setDestroyedListener(null);
                        colorDialog.destory();
                    }
                    colorDialog = null;
                    System.gc();
                    showDialog_ColorSelector();
                }
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        });
        text_ForegroundSelector = (Text) findComponentById(ResourceTable.Id_emptyBox_foregroundSelector);
        text_ForegroundSelector.setText("Empty");
        text_ForegroundSelector.setClickedListener(c ->
        {
            if(!isProcessing)
            {
                try
                {
                    if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                        showPermissionRequest();
                    else
                        selectPic(ChooseImage_Foreground);
                }catch(Exception ex){}
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        });
        text_BackgroundSelector = (Text) findComponentById(ResourceTable.Id_emptyBox_backgroundSelector);
        text_BackgroundSelector.setText("Empty");
        text_BackgroundSelector.setClickedListener(c ->
        {
            if(!isProcessing)
            {
                try
                {
                    if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                        showPermissionRequest();
                    else
                        selectPic(ChooseImage_Background);
                }catch(Exception ex){}
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        });
        text_IconSize = (Text) findComponentById(ResourceTable.Id_text_iconSize);
        SizeSlider = (Slider) findComponentById(ResourceTable.Id_slider_iconSize);
        SizeSlider.setMinValue(0);
        SizeSlider.setMaxValue(3);
        DatabaseManager.Init(getContext());
        int R_value = DatabaseManager.getInt("IconElementSize",3);
        SizeSlider.setProgressValue(R_value);
        text_IconSize.setText(ResourceTool.getString(getContext(),ResourceTable.String_SmartIcon_IconSize,"元素尺寸（[值]）").replaceFirst("\\[值\\]","Level"+R_value));
        SizeSlider.setStep(1);
        SizeSlider.setValueChangedListener(new Slider.ValueChangedListener()
        {
            @Override
            public void onProgressUpdated(Slider slider, int i, boolean b)
            {
                DatabaseManager.Init(getContext());
                DatabaseManager.setInt("IconElementSize",i);
                if(i==0)DatabaseManager.setInt("IconElementRealSize",96);
                else if(i==1)DatabaseManager.setInt("IconElementRealSize",120);
                else if(i==2)DatabaseManager.setInt("IconElementRealSize",154);
                else DatabaseManager.setInt("IconElementRealSize",192);
                text_IconSize.setText(ResourceTool.getString(getContext(),ResourceTable.String_SmartIcon_IconSize,"元素尺寸（[值]）").replaceFirst("\\[值\\]","Level"+i));
            }

            @Override
            public void onTouchStart(Slider slider) {}
            @Override
            public void onTouchEnd(Slider slider) {}
        });
        mask_method01 = findComponentById(ResourceTable.Id_mask_01);
        mask_method02 = findComponentById(ResourceTable.Id_mask_02);
        mask_method03 = findComponentById(ResourceTable.Id_mask_03);
        mask_method04 = findComponentById(ResourceTable.Id_mask_04);
        mask_method05 = (Image) findComponentById(ResourceTable.Id_mask_05);
        mask_border01 = findComponentById(ResourceTable.Id_mask_border01);
        mask_border02 = findComponentById(ResourceTable.Id_mask_border02);
        mask_border03 = findComponentById(ResourceTable.Id_mask_border03);
        mask_border04 = findComponentById(ResourceTable.Id_mask_border04);
        mask_border05 = findComponentById(ResourceTable.Id_mask_border05);
        mask_method01.setClickedListener(c->
        {
            if(!isProcessing)
            {
                MaskMode = 0;
                DatabaseManager.Init(getContext());
                DatabaseManager.setInt("SmartIcon_MaskMode",MaskMode);
                mask_border02.setVisibility(Component.INVISIBLE);
                mask_border03.setVisibility(Component.INVISIBLE);
                mask_border04.setVisibility(Component.INVISIBLE);
                mask_border05.setVisibility(Component.INVISIBLE);
                mask_border01.setVisibility(Component.VISIBLE);
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();

        });
        mask_method02.setClickedListener(c->
        {
            if(!isProcessing)
            {
                MaskMode = 1;
                DatabaseManager.Init(getContext());
                DatabaseManager.setInt("SmartIcon_MaskMode",MaskMode);
                mask_border01.setVisibility(Component.INVISIBLE);
                mask_border03.setVisibility(Component.INVISIBLE);
                mask_border04.setVisibility(Component.INVISIBLE);
                mask_border05.setVisibility(Component.INVISIBLE);
                mask_border02.setVisibility(Component.VISIBLE);
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        });
        mask_method03.setClickedListener(c->
        {
            if(!isProcessing)
            {
                MaskMode = 2;
                DatabaseManager.Init(getContext());
                DatabaseManager.setInt("SmartIcon_MaskMode",MaskMode);
                mask_border01.setVisibility(Component.INVISIBLE);
                mask_border02.setVisibility(Component.INVISIBLE);
                mask_border04.setVisibility(Component.INVISIBLE);
                mask_border05.setVisibility(Component.INVISIBLE);
                mask_border03.setVisibility(Component.VISIBLE);
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        });
        mask_method04.setClickedListener(c->
        {
            if(!isProcessing)
            {
                MaskMode = 3;
                DatabaseManager.Init(getContext());
                DatabaseManager.setInt("SmartIcon_MaskMode",MaskMode);
                mask_border01.setVisibility(Component.INVISIBLE);
                mask_border02.setVisibility(Component.INVISIBLE);
                mask_border03.setVisibility(Component.INVISIBLE);
                mask_border05.setVisibility(Component.INVISIBLE);
                mask_border04.setVisibility(Component.VISIBLE);
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        });
        pxm = GeneralUtil.getPixelMapFromResource(this,ResourceTable.Media_symbol_add);
        mask_method05.setBackground(new ShapeElement(getContext(),ResourceTable.Graphic_pic_base));
        mask_method05.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
        mask_method05.setPixelMap(pxm);
        mask_method05.setClickedListener(c ->
        {
            if(!isProcessing)
            {
                try
                {
                    if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                        showPermissionRequest();
                    else
                        selectPic(ChooseImage_Mask);
                }catch(Exception ex){}
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        });
        DatabaseManager.Init(this);
        MaskMode = DatabaseManager.getInt("SmartIcon_MaskMode",0);
        if(MaskMode==0)
        {
            mask_border01.setVisibility(Component.VISIBLE);
            mask_border02.setVisibility(Component.INVISIBLE);
            mask_border03.setVisibility(Component.INVISIBLE);
            mask_border04.setVisibility(Component.INVISIBLE);
            mask_border05.setVisibility(Component.INVISIBLE);
        }else if(MaskMode==1)
        {
            mask_border01.setVisibility(Component.INVISIBLE);
            mask_border02.setVisibility(Component.VISIBLE);
            mask_border03.setVisibility(Component.INVISIBLE);
            mask_border04.setVisibility(Component.INVISIBLE);
            mask_border05.setVisibility(Component.INVISIBLE);
        }else if(MaskMode==2)
        {
            mask_border01.setVisibility(Component.INVISIBLE);
            mask_border02.setVisibility(Component.INVISIBLE);
            mask_border03.setVisibility(Component.VISIBLE);
            mask_border04.setVisibility(Component.INVISIBLE);
            mask_border05.setVisibility(Component.INVISIBLE);
        }else if(MaskMode==3)
        {
            mask_border01.setVisibility(Component.INVISIBLE);
            mask_border02.setVisibility(Component.INVISIBLE);
            mask_border03.setVisibility(Component.INVISIBLE);
            mask_border04.setVisibility(Component.VISIBLE);
            mask_border05.setVisibility(Component.INVISIBLE);
        }else if(MaskMode==4)
        {
            File MaskImageFile = new File(getCacheDir() + "/SmartIcon/Mask.png");
            if(MaskImageFile.exists())
            {
                PixelMap pixelMap_rec = GeneralUtil.getPixelMapFromFile(MaskImageFile);
                if(pixelMap_rec != null)
                {
                    mask_method05.setBackground(null);
                    mask_method05.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                    mask_method05.setPixelMap(pixelMap_rec);
                    mask_border01.setVisibility(Component.INVISIBLE);
                    mask_border02.setVisibility(Component.INVISIBLE);
                    mask_border03.setVisibility(Component.INVISIBLE);
                    mask_border04.setVisibility(Component.INVISIBLE);
                    mask_border05.setVisibility(Component.VISIBLE);
                }else
                {
                    MaskMode = 0;
                    mask_border01.setVisibility(Component.VISIBLE);
                    mask_border02.setVisibility(Component.INVISIBLE);
                    mask_border03.setVisibility(Component.INVISIBLE);
                    mask_border04.setVisibility(Component.INVISIBLE);
                    mask_border05.setVisibility(Component.INVISIBLE);
                }
            }
            else
            {
                DatabaseManager.Init(this);
                String UriString = DatabaseManager.getString("SmartIconAbility_ImageUri_Mask","None");
                if(!UriString.equals("None"))
                {
                    Uri uri_rec = Uri.parse(UriString);
                    PixelMap pixelMap_rec = ImageIntelligent.ObtainImage(uri_rec,this);
                    if(pixelMap_rec != null)
                    {
                        ImageIntelligent.saveImage(getContext(),uri_rec,getCacheDir() + "/SmartIcon/Mask.png");
                        if(MaskImageFile.exists())
                        {
                            mask_method05.setBackground(null);
                            mask_method05.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                            mask_method05.setPixelMap(pixelMap_rec);
                            mask_border01.setVisibility(Component.INVISIBLE);
                            mask_border02.setVisibility(Component.INVISIBLE);
                            mask_border03.setVisibility(Component.INVISIBLE);
                            mask_border04.setVisibility(Component.INVISIBLE);
                            mask_border05.setVisibility(Component.VISIBLE);
                        }else
                        {
                            MaskMode = 0;
                            mask_border01.setVisibility(Component.VISIBLE);
                            mask_border02.setVisibility(Component.INVISIBLE);
                            mask_border03.setVisibility(Component.INVISIBLE);
                            mask_border04.setVisibility(Component.INVISIBLE);
                            mask_border05.setVisibility(Component.INVISIBLE);
                        }
                    }else
                    {
                        MaskMode = 0;
                        mask_border01.setVisibility(Component.VISIBLE);
                        mask_border02.setVisibility(Component.INVISIBLE);
                        mask_border03.setVisibility(Component.INVISIBLE);
                        mask_border04.setVisibility(Component.INVISIBLE);
                        mask_border05.setVisibility(Component.INVISIBLE);
                    }
                }else
                {
                    MaskMode = 0;
                    mask_border01.setVisibility(Component.VISIBLE);
                    mask_border02.setVisibility(Component.INVISIBLE);
                    mask_border03.setVisibility(Component.INVISIBLE);
                    mask_border04.setVisibility(Component.INVISIBLE);
                    mask_border05.setVisibility(Component.INVISIBLE);
                }
            }
        }else
        {
            MaskMode = 0;
            mask_border01.setVisibility(Component.VISIBLE);
            mask_border02.setVisibility(Component.INVISIBLE);
            mask_border03.setVisibility(Component.INVISIBLE);
            mask_border04.setVisibility(Component.INVISIBLE);
            mask_border05.setVisibility(Component.INVISIBLE);
        }
        Button Button_StartProcess= (Button) findComponentById(ResourceTable.Id_Button_StartProcess);
        int spacingHorizontal = (int) ResourceTool.getFloat(this, ResourceTable.Float_spacing_ui_button, 0);
        Button_StartProcess.setBackground(new GeneralButtonElement(this, GeneralButtonElement.TYPE_UI_Button));
        Button_StartProcess.setTextColor(new Color(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_button_text_accent, 0xFFFFFF)));
        Button_StartProcess.setMultipleLine(false);
        Button_StartProcess.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
        Button_StartProcess.setPaddingLeft(spacingHorizontal);
        Button_StartProcess.setPaddingRight(spacingHorizontal);
        Button_StartProcess.setClickedListener(c->
        {
            if(!isProcessing)
            {
                if(textBox_ChineseName.getText().equals("")&&textBox_InternationalName.getText().equals(""))
                    new GeneralToast(this).setText(Toast_NoneName).show();
                else if(textBox_DesignerName.getText().equals(""))
                    new GeneralToast(this).setText(Toast_NoneDesigner).show();
                else if(textBox_VersionCode.getText().equals(""))
                    new GeneralToast(this).setText(Toast_NoneVersion).show();
                else if(textBox_BriefInfo.getText().equals(""))
                    new GeneralToast(this).setText(Toast_NoneBriefInfo).show();
                else if(!PreloadServiceAbility.isSuccess)
                {
                    try
                    {
                        Intent e = new Intent();
                        //通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                        Operation operation = new Intent.OperationBuilder()
                                .withBundleName("com.agger.harmonyosthemeseditor")
                                .withAbilityName("com.agger.harmonyosthemeseditor.abilities.PreloadServiceAbility")
                                .build();
                        // 把operation设置到intent中
                        e.setOperation(operation);
                        startAbility(e);
                    }catch (Exception ex){}
                    new GeneralToast(this).setText(ResourceTool.getString(this,ResourceTable.String_ThemeToast_EnvironmentNotReady,"智慧意识未就绪，请确保必要支持库已成功部署！")).show();
                }else if(verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                    showPermissionRequest();
                else
                {
                    isProcessing = true;
                    textBox_ChineseName.setEnabled(false);
                    textBox_InternationalName.setEnabled(false);
                    textBox_DesignerName.setEnabled(false);
                    textBox_VersionCode.setEnabled(false);
                    textBox_BriefInfo.setEnabled(false);
                    SizeSlider.setEnabled(false);
                    textBox_ChineseName.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                    textBox_InternationalName.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                    textBox_DesignerName.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                    textBox_VersionCode.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                    textBox_BriefInfo.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                    if(textBox_ChineseName.getText().equals("")) textBox_ChineseName.setText(textBox_InternationalName.getText());
                    else if(textBox_InternationalName.getText().equals("")) textBox_InternationalName.setText(textBox_ChineseName.getText());
                    String ThemeVersion = textBox_VersionCode.getText();
                    if(!ThemeVersion.contains("."))
                    {
                        ThemeVersion += ".0";
                    }else if(ThemeVersion.endsWith("."))
                    {
                        ThemeVersion += "0";
                    }
                    if(ThemeVersion.startsWith("0.")||ThemeVersion.startsWith("1.")||ThemeVersion.startsWith("2.")||ThemeVersion.startsWith("3.")||ThemeVersion.startsWith("4.")||ThemeVersion.startsWith("5.")||ThemeVersion.startsWith("6.")||ThemeVersion.startsWith("7.")||ThemeVersion.startsWith("8.")||ThemeVersion.startsWith("9.")||ThemeVersion.startsWith("10.")||ThemeVersion.startsWith("11."))
                    {
                        ThemeVersion = "12"+ThemeVersion.substring(ThemeVersion.indexOf('.'));
                    }
                    textBox_VersionCode.setText(ThemeVersion);
                    screenEventHandler.sendSyncEvent(1,EventHandler.Priority.IMMEDIATE);
                    PacThemeEventHandler.sendEvent(0, 0, EventHandler.Priority.IMMEDIATE);
                }
            }else
            {
                new GeneralToast(this).setText(Toast_IsProcessing).show();
            }
        });
        findComponentById(ResourceTable.Id_actionBar_Back).setClickedListener(c->onBackPressed());
        DatabaseManager.Init(this);
        String Ability_QuitBySelf = DatabaseManager.getString("SmartIconAbility_QuitBySelf","No");
        if(!Ability_QuitBySelf.equals("Yes"))
        {
            File ForegroundFile = new File(getCacheDir() + "/SmartIcon/Foreground.png");
            if(!ForegroundFile.exists())
            {
                String UriString = DatabaseManager.getString("SmartIconAbility_ImageUri_Foreground","None");
                if(!UriString.equals("None"))
                {
                    Uri uri_rec =Uri.parse(UriString);
                    PixelMap pixelMap_rec = ImageIntelligent.ObtainImage(uri_rec,this);
                    if(pixelMap_rec != null)
                    {
                        ImageIntelligent.saveImage(getContext(),uri_rec,getCacheDir() + "/SmartIcon/Foreground.png");
                        if(ForegroundFile.exists())text_ForegroundSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                    }
                }
            }else
                text_ForegroundSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
            File BackgroundFile = new File(getCacheDir() + "/SmartIcon/Background.png");
            if(!BackgroundFile.exists())
            {
                String UriString = DatabaseManager.getString("SmartIconAbility_ImageUri_Background","None");
                if(!UriString.equals("None"))
                {
                    Uri uri_rec =Uri.parse(UriString);
                    PixelMap pixelMap_rec = ImageIntelligent.ObtainImage(uri_rec,this);
                    if(pixelMap_rec != null)
                    {
                        ImageIntelligent.saveImage(getContext(),uri_rec,getCacheDir() + "/SmartIcon/Background.png");
                        if(BackgroundFile.exists())text_BackgroundSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                    }
                }
            }else
                text_BackgroundSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
        }
        DatabaseManager.setString("SmartIconAbility_QuitBySelf","No");
        if(text_ForegroundSelector.getText().equals("Empty")&&new File(getCacheDir() + "/SmartIcon/Foreground.png").exists()){FileManager.deleteFile(getCacheDir() + "/SmartIcon/Foreground.png");}
        if(text_BackgroundSelector.getText().equals("Empty")&&new File(getCacheDir() + "/SmartIcon/Background.png").exists()){FileManager.deleteFile(getCacheDir() + "/SmartIcon/Background.png");}

        PacThemeEventHandler = new PacThemeEventHandler(EventRunner.create(true));
    }

    @Override
    public void onBackPressed()
    {
        if(!isProcessing)
        {
            DatabaseManager.Init(this);
            DatabaseManager.setString("LastAbilityName","None");
            DatabaseManager.setString("SmartIconAbility_QuitBySelf","Yes");
            DatabaseManager.setString("SmartIconAbility_ImageUri_Foreground", "None");
            DatabaseManager.setString("SmartIconAbility_ImageUri_Background", "None");
            DatabaseManager.setString("SmartIconAbility_VideoUri", "None");
            try{getWindow().setNavigationBarColor(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_navigationbar_bottom, 0xF5F1E6));}catch (Exception ex){}
            ThemesEditorAbility.isMainSceneSlice = true;
            try{mask_method05.release();}catch(Exception e){}
            try{pxm.release();}catch(Exception e){}
            try{textBox_ChineseName.release();}catch(Exception e){}
            try{textBox_InternationalName.release();}catch(Exception e){}
            try{textBox_DesignerName.release();}catch(Exception e){}
            try{textBox_VersionCode.release();}catch(Exception e){}
            try{textBox_BriefInfo.release();}catch(Exception e){}
            try{text_ChineseName.release();}catch(Exception e){}
            try{text_InternationalName.release();}catch(Exception e){}
            try{text_DesignerName.release();}catch(Exception e){}
            try{text_VersionCode.release();}catch(Exception e){}
            try{mask_border01.release();}catch(Exception e){}
            try{mask_method01.release();}catch(Exception e){}
            try{mask_border02.release();}catch(Exception e){}
            try{mask_method02.release();}catch(Exception e){}
            try{mask_border03.release();}catch(Exception e){}
            try{mask_method03.release();}catch(Exception e){}
            try{mask_border04.release();}catch(Exception e){}
            try{mask_method04.release();}catch(Exception e){}
            try{mask_border05.release();}catch(Exception e){}
            try{mask_method05.release();}catch(Exception e){}
            try{text_ColorSelector.release();}catch(Exception e){}
            try{text_ForegroundSelector.release();}catch(Exception e){}
            try{text_BackgroundSelector.release();}catch(Exception e){}
            try{text_IconSize.release();}catch(Exception e){}
            try{SizeSlider.release();}catch(Exception e){}
            pxm = null;
            textBox_ChineseName = null;
            textBox_InternationalName = null;
            textBox_DesignerName = null;
            textBox_VersionCode = null;
            textBox_BriefInfo = null;
            text_ChineseName = null;
            text_InternationalName = null;
            text_DesignerName = null;
            text_VersionCode = null;
            mask_border01 = null;
            mask_method01 = null;
            mask_border02 = null;
            mask_method02 = null;
            mask_border03 = null;
            mask_method03 = null;
            mask_border04 = null;
            mask_method04 = null;
            mask_border05 = null;
            mask_method05 = null;
            Dialog_Title = null;
            Dialog_Content_StoragePermissionFailed = null;
            Dialog_Button_Cancel = null;
            Dialog_Button_Confirm = null;
            Toast_NoneName = null;
            Toast_NoneDesigner = null;
            Toast_NoneVersion = null;
            Toast_NoneBriefInfo = null;
            Toast_IsProcessing = null;
            Toast_Theme_SaveFinish = null;
            Toast_Theme_SaveFailed = null;
            mainThreadEventHandler = null;
            PacThemeEventHandler = null;
            screenEventHandler = null;
            text_ColorSelector = null;
            text_ForegroundSelector = null;
            text_BackgroundSelector = null;
            text_IconSize = null;
            SizeSlider = null;
            ElementColor = null;
            System.gc();
            if(ThemesEditorAbility.LayoutChanged)
            {
                ThemesEditorAbility.LayoutChanged = false;
                try{MainSceneSlice.Instance.restart();}catch (Exception ex){}
            }
            else
            {
                try{MainSceneSlice.Instance.pageSwiper.ReturnImageSwiper_Industry(true);}catch (Exception ex){}
            }
            super.onBackPressed();
        }else
        {
            new GeneralToast(this).setText(Toast_IsProcessing).show();
        }
    }

    private CommonDialog.DestroyedListener colorSelectorListener()
    {
        return () ->
        {
            try
            {
                DatabaseManager.Init(this);
                ElementColor = ColorManager.getColorHex(colorDialog.getColorValue());
                text_ColorSelector.setText("#"+ElementColor);
                DatabaseManager.setString("SmartIcon_ElementColor",ElementColor);
            }catch (Exception ex){}
        };
    }

    private void showDialog_ColorSelector()
    {
        colorDialog = new ColorDialog(this);
        colorDialog.setDestroyedListener(colorSelectorListener());
        colorDialog
                .setTitle(ResourceTool.getString(this,ResourceTable.String_Dialog_SelectorColor,"选择颜色"))
                .setCloseText(ResourceTool.getString(this,ResourceTable.String_Dialog_text_close,"关闭"))
                .setDefaultColor(text_ColorSelector.getText())
                .setOutsideTouchClosable(false)
                .show();
    }

    private void recoverDialog_ColorSelector()
    {
        DatabaseManager.Init(getContext());
        colorDialog = new ColorDialog(this);
        colorDialog.setDestroyedListener(colorSelectorListener());
        colorDialog
                .setTitle(ResourceTool.getString(this,ResourceTable.String_Dialog_SelectorColor,"选择颜色"))
                .setCloseText(ResourceTool.getString(this,ResourceTable.String_Dialog_text_close,"关闭"))
                .setDefaultColor(DatabaseManager.getInt("ColorDialog_TempColorValue",-1))
                .setOutsideTouchClosable(false)
                .show();
    }

    public void PermissionRouter(GeneralDialog dialog)
    {
        Intent e = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction(IntentConstants.ACTION_APPLICATION_DETAILS_SETTINGS)
                .withUri(Uri.getUriFromParts("package",getBundleName(),null))
                .build();
        e.setOperation(operation);
        startAbility(e);
        dialog.remove();
    }

    private void showPermissionRequest()
    {
        if (canRequestPermission("ohos.permission.READ_USER_STORAGE") && canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
            requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_USER_STORAGE"}, 2);
        else
        {
            GeneralDialog.Builder builder = new GeneralDialog.Builder(getContext());
            builder.setTitle(Dialog_Title)
                    .setContent(Dialog_Content_StoragePermissionFailed)
                    .addButton(Dialog_Button_Cancel, GeneralButtonElement.TYPE_NORMAL, GeneralDialog::remove)
                    .addButton(Dialog_Button_Confirm, GeneralButtonElement.TYPE_ACCENT, this::PermissionRouter)
                    .setOutsideTouchClosable(false)
                    .setMovable(false)
                    .create()
                    .show();
        }
    }
    
    private void selectPic(int fileMode)
    {
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder()
                .withAction("android.intent.action.OPEN_DOCUMENT")
                .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                .build();
        intent.setOperation(opt);
        intent.setType(fileMode==ChooseImage_Mask?"image/png":"image/*");
        startAbilityForResult(intent,fileMode);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData)
    {
        if(requestCode==ChooseImage_Mask)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String ImageUri=resultData.getUriString();
                Uri targetUri;
                DatabaseManager.Init(this);
                if(ImageUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                    DatabaseManager.setString("SmartIconAbility_ImageUri_Mask", ImageUri);
                }else
                {
                    String ImageId;
                    if(ImageUri.lastIndexOf("%3A")!=-1)ImageId = ImageUri.substring(ImageUri.lastIndexOf("%3A")+3);
                    else ImageId = ImageUri.substring(ImageUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,ImageId);
                    DatabaseManager.setString("SmartIconAbility_ImageUri_Mask",targetUri.toString());
                }
                try
                {
                    PixelMap pixelMap = ImageIntelligent.ObtainImage(targetUri,getContext());
                    String workPath = getCacheDir() + "/SmartIcon";
                    if(!new File(workPath).exists())new File(workPath).mkdirs();
                    ImageIntelligent.saveImage(getContext(),targetUri,workPath+"/Mask.png");
                    if(new File(workPath+"/Mask.png").exists())
                    {
                        mask_method05.setBackground(null);
                        mask_method05.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                        mask_method05.setPixelMap(pixelMap);
                        MaskMode = 4;
                        DatabaseManager.Init(getContext());
                        DatabaseManager.setInt("SmartIcon_MaskMode",MaskMode);
                        mask_border01.setVisibility(Component.INVISIBLE);
                        mask_border02.setVisibility(Component.INVISIBLE);
                        mask_border03.setVisibility(Component.INVISIBLE);
                        mask_border04.setVisibility(Component.INVISIBLE);
                        mask_border05.setVisibility(Component.VISIBLE);
                    }
                } catch (Exception e) {} finally {}
            }catch (Exception e){}
        }else if(requestCode==ChooseImage_Foreground)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String ImageUri=resultData.getUriString();
                Uri targetUri;
                DatabaseManager.Init(this);
                if(ImageUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                    DatabaseManager.setString("SmartIconAbility_ImageUri_Foreground", ImageUri);
                }else
                {
                    String ImageId;
                    if(ImageUri.lastIndexOf("%3A")!=-1)ImageId = ImageUri.substring(ImageUri.lastIndexOf("%3A")+3);
                    else ImageId = ImageUri.substring(ImageUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,ImageId);
                    DatabaseManager.setString("SmartIconAbility_ImageUri_Foreground",targetUri.toString());
                }
                try
                {
                    String workPath = getCacheDir() + "/SmartIcon";
                    if(!new File(workPath).exists())new File(workPath).mkdirs();
                    ImageIntelligent.saveImage(getContext(),targetUri,workPath+"/Foreground.png");
                    if(new File(workPath+"/Foreground.png").exists())
                    {
                        text_ForegroundSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                        //if(!IconManager.isAlphaImage(GeneralUtil.getPixelMapFromFile(new File(workPath+"/Foreground.png"))))
                        //    new GeneralToast(getContext()).setText(ResourceTool.getString(getContext(),ResourceTable.String_IToast_ForegroundNoneAlpha,"智慧助手：请注意，所选图片不包含任何透明度，以此作为前景，将全面遮挡图标元素！")).show();
                    }
                } catch (Exception e) {}
            }catch (Exception e){}
        }else if(requestCode==ChooseImage_Background)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String ImageUri=resultData.getUriString();
                Uri targetUri;
                DatabaseManager.Init(this);
                if(ImageUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                    DatabaseManager.setString("SmartIconAbility_ImageUri_Background", ImageUri);
                }else
                {
                    String ImageId;
                    if(ImageUri.lastIndexOf("%3A")!=-1)ImageId = ImageUri.substring(ImageUri.lastIndexOf("%3A")+3);
                    else ImageId = ImageUri.substring(ImageUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,ImageId);
                    DatabaseManager.setString("SmartIconAbility_ImageUri_Background",targetUri.toString());
                }
                try
                {
                    String workPath = getCacheDir() + "/SmartIcon";
                    if(!new File(workPath).exists())new File(workPath).mkdirs();
                    ImageIntelligent.saveImage(getContext(),targetUri,workPath+"/Background.png");
                    if(new File(workPath+"/Background.png").exists())
                    {
                        text_BackgroundSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                    }
                } catch (Exception e) {}
            }catch (Exception e){}
        }
    }

    @Override
    public void onActive() {super.onActive();}

    @Override
    public void onForeground(Intent intent) {super.onForeground(intent);}
}